/*
 * VentanaNuevoCanal.java
 *
 * Created on 23 de septiembre de 2008, 23:17
 */

package vista;

//import controlador.ControladorAlta;
//import controlador.ControladorConsulta;
//import datos.Modificacion;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import dominio.Canal;
import vista.util.VentanaNuevoCanalUtil;

/**
 *
 * @author  marcelo
 */
public class VentanaNuevoCanal extends javax.swing.JFrame 
{
    private Collection canales = new ArrayList();
    private boolean seleccionado;
    private VentanaNuevoCanalUtil util = new VentanaNuevoCanalUtil();
    private VentanaAgregarCanal ventana = new VentanaAgregarCanal();
    private boolean origen;

    /** Creates new form VentanaNuevoCanal */
    public VentanaNuevoCanal()
    {
        initComponents();
        this.inicializar();
        this.seleccionado = false;
        this.origen = false;
    }

    public VentanaNuevoCanal(VentanaAgregarCanal ventana)
    {
        initComponents();
        this.inicializar();
        this.ventana = ventana;
        this.seleccionado = false;
        this.origen = true;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableCanales = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldNombre = new javax.swing.JTextField();
        jTextFieldFrecuencia = new javax.swing.JTextField();
        jButtonGuardar = new javax.swing.JButton();
        jButtonSalir = new javax.swing.JButton();
        jButtonModificar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nuevo Canal");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Canales"));

        jTableCanales.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Nombre", "Frec."
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableCanales.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableCanalesMouseClicked(evt);
            }
        });
        jTableCanales.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTableCanalesKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTableCanales);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Nuevo Canal"));

        jLabel1.setBackground(new java.awt.Color(255, 255, 204));
        jLabel1.setText("Nombre");
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel1.setOpaque(true);

        jLabel2.setBackground(new java.awt.Color(255, 255, 204));
        jLabel2.setText("Frecuencia");
        jLabel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel2.setOpaque(true);

        jTextFieldFrecuencia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldFrecuenciaActionPerformed(evt);
            }
        });

        jButtonGuardar.setText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonSalir.setText("Salir");
        jButtonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalirActionPerformed(evt);
            }
        });

        jButtonModificar.setText("Modificar");
        jButtonModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModificarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldFrecuencia, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(81, 81, 81))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(38, 38, 38)
                        .addComponent(jButtonModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                        .addComponent(jButtonSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldFrecuencia, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonGuardar)
                    .addComponent(jButtonSalir)
                    .addComponent(jButtonModificar)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalirActionPerformed
// TODO add your handling code here:
    if(this.origen)
        this.ventana.llenarTabla();
    this.dispose();
}//GEN-LAST:event_jButtonSalirActionPerformed

private void jTextFieldFrecuenciaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldFrecuenciaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldFrecuenciaActionPerformed

private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
// TODO add your handling code here:
    this.guardar();
}//GEN-LAST:event_jButtonGuardarActionPerformed

/**
 * Al presionar una tecla, si esta no es la tecla Enter, el sistema va guardando el numero de fila sobre la que se presiono la tecla.
 * Cuando se presiona la tecla Enter, se llama al metodo de modificar y se pasa como parametro el valor de la fila sobre
 * la que se hizo la ultima modificacion.
 * @param evt tecla que fue presionada
 */
private void jTableCanalesKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableCanalesKeyReleased

    if(evt.getKeyCode() == 127)
        this.eliminar();
    
}//GEN-LAST:event_jTableCanalesKeyReleased

private void jTableCanalesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableCanalesMouseClicked
// TODO add your handling code here:
    this.seleccionado = true;
    this.seleccionarFila();
}//GEN-LAST:event_jTableCanalesMouseClicked

private void jButtonModificarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonModificarActionPerformed
{//GEN-HEADEREND:event_jButtonModificarActionPerformed
    // TODO add your handling code here:
    this.modificar();
}//GEN-LAST:event_jButtonModificarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaNuevoCanal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonModificar;
    private javax.swing.JButton jButtonSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableCanales;
    private javax.swing.JTextField jTextFieldFrecuencia;
    private javax.swing.JTextField jTextFieldNombre;
    // End of variables declaration//GEN-END:variables

    /////////////////// INICIALIZACION DE FORMULARIO ////////////////////
    private void inicializar()
    {
        this.centrar();
        this.ajustarTamanioColumna();
        this.limpiar();
        this.cargarTabla();
    }
    
    private void centrar()
    {
        Dimension pantalla, cuadro;
	pantalla = Toolkit.getDefaultToolkit().getScreenSize();
	cuadro = this.getSize();
	this.setLocation(((pantalla.width - cuadro.width)/2), (pantalla.height - cuadro.height)/2);
    }
    
    private void ajustarTamanioColumna()
    {
        TableColumn column = null;
        for (int i = 0; i < 3; i++) 
        {
            column = jTableCanales.getColumnModel().getColumn(i);
            switch(i)
            {
                case 0:
                        column.setPreferredWidth(15);
                        break;
                case 1:
                        column.setPreferredWidth(238);
                        break;
                case 2:
                        column.setPreferredWidth(15);
                        break;
            }
        }
    }

    private void cargarTabla()
    {
        this.canales = this.util.traerTodos(jTableCanales, canales);
    }
    
    /**
     * Metodo para limpiar los registros de la tabla.
     * Quita todas las filas de la tabla.
     */
    private void limpiar()
    {
        DefaultTableModel modelo = (DefaultTableModel)this.jTableCanales.getModel();
        while(this.jTableCanales.getRowCount() != 0)
                modelo.removeRow(0);
        modelo = null;
    }
    
    
    ////////////// GUARDAR REGISTRO /////////////////////////////////
    
    private boolean verificaBlancos()
    {
     boolean bandera = true;
     String var;
     var= this.jTextFieldNombre.getText();
     if ( var.trim().length()== 0)
         bandera = false;
     var = this.jTextFieldFrecuencia.getText();
     if ( var.trim().length()== 0)
         bandera = false;
     return bandera;
    }


    /**
     * este metodo se encarga de guardar el nuevo canal ingresado por el usuario.
     * Basicamente comprende 2 procesos:
     * 1)_ Controlar que todos los campos solicitados esten cargados.
     * 2)_ Guardar el nuevo registro.
     */
    private void guardar()
    {
        if (this.verificaBlancos()) // verifica si todos los campos estan cargados
        {
            Canal c = new Canal();
            c.setFrecuencia(Integer.parseInt(this.jTextFieldFrecuencia.getText().trim()));
            c.setNombreCanal(this.jTextFieldNombre.getText().trim().toUpperCase());
            this.util.nuevoCanal(c);
            this.jTextFieldNombre.setText("");
            this.jTextFieldFrecuencia.setText("");
            this.jTextFieldNombre.requestFocus();
            this.limpiar();
            this.cargarTabla();
        }
        else
            JOptionPane.showMessageDialog(null, "Asegurese de que los campos esten llenos","Hay campos en blancos",JOptionPane.ERROR_MESSAGE);
    }

    private void modificar()
    {
        if(this.verificaBlancos() && this.seleccionado)
        {
            this.util.modificarCanal(this.getCanal());
            this.jTextFieldNombre.setText("");
            this.jTextFieldFrecuencia.setText("");
            this.jTextFieldNombre.requestFocus();
            this.limpiar();
            this.cargarTabla();
        }
        else
            JOptionPane.showMessageDialog(null, "Debe seleccionar un tema para modificar","No hay tema selecionado",JOptionPane.ERROR_MESSAGE);
    }

    ///////////////////////////////// mostrar datos seleccionados del grid

    private void seleccionarFila()
    {
        this.jTextFieldFrecuencia.setText(String.valueOf(this.jTableCanales.getValueAt(this.jTableCanales.getSelectedRow(), 2)).toUpperCase());
        this.jTextFieldNombre.setText(String.valueOf(this.jTableCanales.getValueAt(this.jTableCanales.getSelectedRow(), 1)).toUpperCase());
    }

    private Canal getCanal()
    {
        int codigo = Integer.parseInt(String.valueOf(this.jTableCanales.getValueAt(this.jTableCanales.getSelectedRow(), 0)));
        Canal c = new Canal();
        c.setCodigo(codigo);
        c.setFrecuencia(Integer.parseInt(this.jTextFieldFrecuencia.getText()));
        c.setNombre(this.jTextFieldNombre.getText());
        return c;
    }


    private void eliminar()
    {
        if(this.verificaBlancos())
        {
            this.util.eliminarCanal(this.getCanal());
            this.jTextFieldNombre.setText("");
            this.jTextFieldFrecuencia.setText("");
            this.jTextFieldNombre.requestFocus();
            this.limpiar();
            this.cargarTabla();
        }
        else
            JOptionPane.showMessageDialog(null, "Debe seleccionar un tema para modificar","No hay tema selecionado",JOptionPane.ERROR_MESSAGE);
    }


    private Canal buscarCanal(int fila)
    {
        Canal ca = new Canal();
        Iterator it = this.canales.iterator();
        while(it.hasNext())
        {
            ca = (Canal)it.next();
            if(ca.getCodigo() == Integer.parseInt(String.valueOf(this.jTableCanales.getValueAt(fila, 0))))
                break;
        }
        return ca;
    }
            
}
